import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * user:likai
 * Date:2022-12-26
 * Time:16:44
 */
@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    private ObjectMapper objectMapper=new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //约定的接口格式
        //约定的json格式
        resp.setContentType("application/json;charset=utf8");
        String blogId=req.getParameter("blogId");
        BlogDao blogDao=new BlogDao();
        if(blogId==null){
            //博客列表页
            List<Blog> blogs=blogDao.selectAll();
            resp.getWriter().write(objectMapper.writeValueAsString(blogs));
        }else{
            //博客详情页
            Blog blog=blogDao.selectOne(Integer.parseInt(blogId));
            resp.getWriter().write(objectMapper.writeValueAsString(blog));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //使用这个方法来实现提交新博客
        //先检查用户的登陆状态
        HttpSession session= req.getSession(false);
        if(session==null){
            resp.setStatus(403);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前未登录");
            return;
        }
        User user=(User)session.getAttribute("user");
        if(user==null){
            resp.setStatus(403);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前未登录");
            return;
        }
        //获取标题和正文
        req.setCharacterEncoding("utf8");
        String title=req.getParameter("title");
        String content=req.getParameter("content");
        //构造blog
        Blog blog=new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setUserId(user.getUserId());
        //blogId自增主键设定，postTime，now设定(blogDao)可以查到
        BlogDao blogDao=new BlogDao();
        blogDao.insert(blog);
        //重定向
        resp.sendRedirect("blog.html");

    }
}
